//
//  YMMainViewController.m
//  列表联动
//
//  Created by 刘家俊 on 2017/7/27.
//  Copyright © 2017年 Andrew. All rights reserved.
//

#import "YMMainViewController.h"
#import "YMFoodModel.h"
#import "YMVegetableModel.h"
#import "YMRightTableViewCell.h"
#import "YMLeftTableViewCell.h"
#import <MJExtension.h>
#import <Masonry.h>

#define LeftTable_Width 100  // 左侧tableView的宽度

@interface YMMainViewController () <UITableViewDataSource, UITableViewDelegate>

/* 左边tableView */
@property (nonatomic, weak) UITableView *leftTabelView;
/* 右边tableView */
@property (nonatomic, weak) UITableView *rightTableView;
@property (nonatomic, strong) NSMutableArray *datasouece;
/** 记录上一次的左边选中的cell */
@property(nonatomic, strong) NSIndexPath *lastPath;


@end

@implementation YMMainViewController

static NSString *LeftCellID = @"YMLeftTableViewCell";
static NSString *RightCellID = @"YMRightTableViewCell";

#pragma mark - 懒加载
- (NSMutableArray *)datasouece
{
    if (!_datasouece) {
        _datasouece = [NSMutableArray new];
    }
    return _datasouece;
}

#pragma mark - 初始化
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"列表联动";
    
    [self reloadData];
    [self setupTableView];
}

#pragma mark - 获取数据
- (void)reloadData
{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"vegetable" ofType:@"json"];
    NSData *data = [NSData dataWithContentsOfFile:path];
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
    NSArray *proprietaryArray = [YMFoodModel mj_objectArrayWithKeyValuesArray:dict[@"farm_vegetable"]];
    [self.datasouece addObjectsFromArray:proprietaryArray];
}

#pragma mark - 创建tableView
- (void)setupTableView
{
    //左边列表
    UITableView *leftTabelView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, LeftTable_Width, SCREENHEIGHT)];
    leftTabelView.dataSource = self;
    leftTabelView.delegate = self;
    
    [leftTabelView registerNib:[UINib nibWithNibName:NSStringFromClass([YMLeftTableViewCell class]) bundle:nil] forCellReuseIdentifier:LeftCellID];
    [self.view addSubview:leftTabelView];
    self.leftTabelView = leftTabelView;
    
    //    // 隐藏单元格分割线
    self.leftTabelView.separatorStyle = UITableViewCellSelectionStyleNone;
    self.leftTabelView.showsVerticalScrollIndicator = NO; // 隐藏滚动条
    //默认选中第一个
    [self.leftTabelView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionNone];
    
    //右边
    UITableView *rightTableView = [[UITableView alloc] initWithFrame:CGRectMake(LeftTable_Width, 0, SCREENWIDTH - LeftTable_Width, SCREENHEIGHT)];
    rightTableView.delegate = self;
    rightTableView.dataSource = self;
    [rightTableView registerNib:[UINib nibWithNibName:NSStringFromClass([YMRightTableViewCell class]) bundle:nil] forCellReuseIdentifier:RightCellID];
    [self.view addSubview:rightTableView];
    self.rightTableView = rightTableView;
    self.rightTableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
    self.rightTableView.scrollIndicatorInsets = self.rightTableView.contentInset;
    
}

#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.leftTabelView == tableView) {
        return 1;
    } else {
        return self.datasouece.count;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.leftTabelView == tableView) {
        return self.datasouece.count;
    } else {
        YMFoodModel *model = self.datasouece[section];
        return model.farmvegetable.count;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.leftTabelView == tableView) {
        return 50;
    } else {
        return 103;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (self.leftTabelView == tableView) {
        return 0;
    } else {
        return 30;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (self.leftTabelView == tableView) {
        return CGFLOAT_MIN;
    } else {
        return CGFLOAT_MIN;
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (self.leftTabelView == tableView) {
        return @"";
    } else {
        return @"我的蔬菜";
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (self.leftTabelView == tableView) {
        return nil;
    } else {
        UIView *headView = [UIView new];
        headView.backgroundColor = YMColorRGBA(254, 230, 206, 1);
        
        UILabel *headLabel = [UILabel new];
        [headView addSubview:headLabel];
        headLabel.textColor = YMOrangeTextColor;
        headLabel.font = [UIFont systemFontOfSize:16];
        
        YMFoodModel *model = self.datasouece[section];
        headLabel.text = model.vegname;
        [headLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.mas_equalTo(headView);
            make.left.mas_equalTo(20);
        }];
        return headView;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.leftTabelView == tableView) {
        YMLeftTableViewCell *leftCell = [tableView dequeueReusableCellWithIdentifier:LeftCellID forIndexPath:indexPath];
        YMFoodModel *model = self.datasouece[indexPath.row];
        leftCell.titleLabel.text = model.vegname;
        leftCell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        NSInteger row = [indexPath row];
        NSInteger oldRow = [self.lastPath row];
        if (row == oldRow && self.lastPath != nil) {
            //选中的cell
            leftCell.contentView.backgroundColor = YMLightYellowColor;
            leftCell.titleLabel.tintColor = YMOrangeTextColor;
        } else {
            leftCell.contentView.backgroundColor = [UIColor clearColor];
            leftCell.titleLabel.textColor = [UIColor blackColor];
        }
        return leftCell;
    } else {
        YMRightTableViewCell *rightCell = [tableView dequeueReusableCellWithIdentifier:RightCellID forIndexPath:indexPath];
        YMFoodModel *foodModel = self.datasouece[indexPath.section];
        YMVegetableModel *model = foodModel.farmvegetable[indexPath.row];
        rightCell.model = model;
        rightCell.selectionStyle = UITableViewCellSelectionStyleNone;
        return rightCell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.leftTabelView == tableView) {
        NSInteger newRow = [indexPath row];
        NSInteger oldRow = (self.lastPath != nil) ? [self.lastPath row] : -1;
        if (newRow != oldRow) {
            YMLeftTableViewCell *newCell = [tableView cellForRowAtIndexPath:indexPath];
            newCell.contentView.backgroundColor = YMLightYellowColor;
            newCell.titleLabel.textColor = YMOrangeTextColor;
            YMLeftTableViewCell *oldCell = [tableView cellForRowAtIndexPath:self.lastPath];
            oldCell.contentView.backgroundColor = [UIColor clearColor];
            oldCell.titleLabel.textColor = [UIColor blackColor];
        }
        
        self.lastPath = indexPath;
        [self.rightTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:[indexPath row]] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView == self.rightTableView) {
        //取出当前显示的最顶部的cell的indexPath
        //当前tableview页面可见的分区属性 indexPathsForVisibleRows
        // 取出显示在 视图 且最靠上 的 cell 的 indexPath
        // 判断tableView是否滑动到最底部
        CGFloat height = scrollView.frame.size.height;
        CGFloat contentOffsetY = scrollView.contentOffset.y;
        CGFloat bottomOffset = scrollView.contentSize.height - contentOffsetY;
        if (bottomOffset <= height) {
            NSIndexPath *bottomIndexPath = [[self.rightTableView indexPathsForVisibleRows] lastObject];
            NSIndexPath *moveIndexPath = [NSIndexPath indexPathForRow:bottomIndexPath.section inSection:0];
            [self.leftTabelView selectRowAtIndexPath:moveIndexPath animated:NO scrollPosition:UITableViewScrollPositionMiddle];
        } else {
            NSIndexPath *topIndexPath = [[self.rightTableView indexPathsForVisibleRows] firstObject];
            NSIndexPath *moveIndexPath = [NSIndexPath indexPathForRow:topIndexPath.section inSection:0];
            [self.leftTabelView selectRowAtIndexPath:moveIndexPath animated:NO scrollPosition:UITableViewScrollPositionMiddle];
        }
        
        return;
    }
}



@end
